package org.flh.book.shop.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.flh.book.shop.common.response.ProTableResponse;
import org.flh.book.shop.common.response.RestResponse;
import org.flh.book.shop.entity.Book;
import org.flh.book.shop.service.BookService;
import org.flh.book.shop.utils.PageUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * 描述：书籍控制器
 *
 * @author 花好月圆
 * @date 2020/11/19 11:15
 */
@RestController
@RequestMapping("/book")
@Api(value = "API - BookController", tags = "书籍")
public class BookController {

    private final BookService bookService;

    public BookController(BookService bookService) {
        this.bookService = bookService;
    }

    @GetMapping("/query/condition")
    @ApiOperation("书籍条件查询")
    public ProTableResponse<Book> queryCondition(
        @ApiParam("书名") @RequestParam(value = "name", required = false) String name,
        @ApiParam("作者") @RequestParam(value = "author", required = false) String author,
        @ApiParam(value = "第几页", example = "1", defaultValue = "1") @RequestParam(value = "currentPage", defaultValue = "1") Integer currentPage,
        @ApiParam(value = "每页多少条数据", example = "10", defaultValue = "10") @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
        return bookService.queryCondition(name, author, PageUtils.buildPage(currentPage, pageSize));
    }

    @PostMapping("/add/book")
    @ApiOperation("新增书籍")
    public RestResponse addBook(@RequestBody Book book) {
        bookService.addBook(book);
        return RestResponse.success();
    }

    @PostMapping("/update/book")
    @ApiOperation("更新书籍")
    public RestResponse updateBook(@RequestBody Book book) {
        bookService.updateBook(book);
        return RestResponse.success();
    }

    @GetMapping("/delete")
    @ApiOperation("删除书籍")
    public RestResponse deleteById(@ApiParam(value = "主键id", example = "0") @RequestParam("id") int id) {
        bookService.deleteById(id);
        return RestResponse.success();
    }

    @PostMapping("/batch/delete")
    @ApiOperation("批量删除")
    public RestResponse batchDelete(@RequestBody List<Integer> idList){
        if (CollectionUtils.isEmpty(idList)) {
            return RestResponse.fail("删除失败，请选择需要删除的书籍。");
        }
        bookService.batchDelete(idList);
        return RestResponse.success();
    }
}
